package com.gaohe.web.controller.scp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.gaohe.common.core.domain.entity.SysUser;
import com.gaohe.system.service.ISysUserService;
import java.util.List;
import java.util.stream.Collectors;

import com.gaohe.common.utils.SecurityUtils;
import com.gaohe.scp.domain.vo.CsNoticeVo;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gaohe.common.annotation.Log;
import com.gaohe.common.core.controller.BaseController;
import com.gaohe.common.core.domain.AjaxResult;
import com.gaohe.common.enums.BusinessType;
import com.gaohe.scp.domain.CsNotice;
import com.gaohe.scp.service.ICsNoticeService;
import com.gaohe.common.utils.poi.ExcelUtil;
import com.gaohe.common.core.page.TableDataInfo;

/**
 * 系统通知Controller
 *
 * @author liuxiangyu
 * @date 2025-03-17
 */
@RestController
@RequestMapping("/scp/notice")
public class CsNoticeController extends BaseController
{
    @Autowired
    private ICsNoticeService csNoticeService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询系统通知列表
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(CsNotice csNotice)
    {
        startPage();
        List<CsNotice> list = csNoticeService.selectCsNoticeList(csNotice);
        return getDataTable(list);
    }

    /**
     * 管理端
     * 查询系统通知列表
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:list')")
    @GetMapping("/list/gld")
    public TableDataInfo listGld(CsNotice csNotice)
    {
        startPage();
        List<CsNotice> csNoticeList = new ArrayList<>();
        Map<Long, String> userId_nickNameMap = new HashMap<>();
        Set<Long> userIdSet = new HashSet<>();
        List<CsNotice> list = csNoticeService.selectCsNoticeList(csNotice);
        if (list.isEmpty()){
            return getDataTable(csNoticeList);
        }
        for (CsNotice notice : list) {
            Long userId = notice.getUserId();
            userIdSet.add(userId);
        }
        List<SysUser> userList = sysUserService.selectUserByIds(userIdSet);
        for (SysUser sysUser : userList) {
            String nickName = sysUser.getNickName();
            Long userId = sysUser.getUserId();
            userId_nickNameMap.put(userId,nickName);
        }
        for (CsNotice notice : list) {
            Long userId = notice.getUserId();
            String nickName = userId_nickNameMap.get(userId);
            notice.setUserName(nickName);
            csNoticeList.add(notice);
        }
        return getDataTable(csNoticeList);
    }

    /**
     * 管理端
     * 导出系统通知列表
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:export')")
    @Log(title = "系统通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export/gld")
    public void exportGld(HttpServletResponse response, CsNotice csNotice)
    {
        List<CsNotice> list = csNoticeService.selectCsNoticeList(csNotice);
        ExcelUtil<CsNotice> util = new ExcelUtil<CsNotice>(CsNotice.class);
        util.exportExcel(response, list, "系统通知数据");
    }

    /**
     * 导出系统通知列表
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:export')")
    @Log(title = "系统通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CsNotice csNotice)
    {
        List<CsNotice> list = csNoticeService.selectCsNoticeList(csNotice);
        ExcelUtil<CsNotice> util = new ExcelUtil<CsNotice>(CsNotice.class);
        util.exportExcel(response, list, "系统通知数据");
    }

    /**
     * 获取系统通知详细信息
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable("noticeId") Long noticeId)
    {
        return success(csNoticeService.selectCsNoticeByNoticeId(noticeId));
    }

//    /**
//     * 新增系统通知
//     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:add')")
//    @Log(title = "系统通知", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody CsNotice csNotice)
//    {
//        return toAjax(csNoticeService.insertCsNotice(csNotice));
//    }

    /**
     * 修改系统通知
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:edit')")
//    @Log(title = "系统通知", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody CsNotice csNotice)
//    {
//        return toAjax(csNoticeService.updateCsNotice(csNotice));
//    }

    /**
     * 删除系统通知
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:remove')")
    @Log(title = "系统通知", businessType = BusinessType.DELETE)
	@DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds)
    {
        return toAjax(csNoticeService.deleteCsNoticeByNoticeIds(noticeIds));
    }
    /**
     * 管理端
     * 获取系统通知详细信息
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:query')")
    @GetMapping(value = "/gld/{noticeId}")
    public AjaxResult getInfoGld(@PathVariable("noticeId") Long noticeId)
    {
        Map<String,Object> map = csNoticeService.selectCsNoticeByNoticeIdMap(noticeId);
        Long userId = (Long) map.get("userId");
        String userName = "";
        if (userId != null){
            SysUser sysUser = sysUserService.selectUserById(userId);
            userName = sysUser.getNickName();
        }
        map.put("userName",userName);
        return success(map);
    }

    /**
     * 管理端
     * 新增系统通知
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:add')")
    @Log(title = "系统通知", businessType = BusinessType.INSERT)
    @PostMapping("gld")
    public AjaxResult add(@RequestBody Map<String, Object> data)
    {
        String content = (String) data.get("content");
        if (content==null){
            return error("请输入内容");
        }

        CsNotice csNotice = new CsNotice();
        Integer userId1 = (Integer) data.get("userId");
        Long userId = null;
        String nickName = null;
        if (userId1 != null) {
            userId = userId1.longValue();
            SysUser sysUser = sysUserService.selectUserById(userId);
            nickName = sysUser.getNickName();
        }

//        Long userId = sysUser.getUserId();
        String type = (String) data.get("type");
        Object time = data.get("publishTime");
        String remark = (String) data.get("remark");
        if (time instanceof Date) {
            Date publishTime = (Date) time;
            csNotice.setPublishTime(publishTime);
        } else if (time instanceof String) {
            try {
                Date publishTime = new SimpleDateFormat("yyyy-MM-dd").parse((String) time);
                csNotice.setPublishTime(publishTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        csNotice.setType(type);
        csNotice.setRemark(remark);
        csNotice.setUserId(userId);
        csNotice.setUserName(nickName);
        int i = csNoticeService.insertCsNotice(csNotice,content);
        return toAjax(i);
    }

    /**
     * 管理端
     * 修改系统通知
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:edit')")
    @Log(title = "系统通知", businessType = BusinessType.UPDATE)
    @PutMapping("/gld")
    public AjaxResult edit(@RequestBody Map<String, Object> data)
    {
        CsNotice csNotice = new CsNotice();
        Object time = data.get("publishTime");
        if (time == null){
            return error("请选择发布时间");
        }
        String content = (String) data.get("content");
//        String s = StringUtils.substringBetween(content, "<p>", "</p>");
//        if (s.equals("<br>")  || s.isBlank()){
//            return error("请输入内容");
//        }
        Integer noticeId1 = (Integer) data.get("noticeId");
        Long noticeId = noticeId1.longValue();

        Integer userId1 = (Integer) data.get("userId");
        Long userId = null;
        String nickName = null;
        if (userId1 != null) {
            userId = userId1.longValue();
            SysUser sysUser = sysUserService.selectUserById(userId);
            nickName = sysUser.getNickName();
        }

//        String userName = (String) data.get("userName");
//        SysUser sysUser = sysUserService.selectUserByNickName(userName);
//        Long userId = sysUser.getUserId();

//        String remark = (String) data.get("remark");
        String type = (String) data.get("type");
        if (time instanceof Date) {
            Date publishTime = (Date) time;
            csNotice.setPublishTime(publishTime);
        } else if (time instanceof String) {
            try {
                Date publishTime = new SimpleDateFormat("yyyy-MM-dd").parse((String) time);
                csNotice.setPublishTime(publishTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        csNotice.setNoticeId(noticeId);
        csNotice.setType(type);
//        csNotice.setRemark(remark);
        csNotice.setUserId(userId);
        csNotice.setUserName(nickName);
        int i = csNoticeService.updateCsNotice(csNotice,content);
        return toAjax(i);
    }

    /**
     * 删除系统通知
     */
//    @PreAuthorize("@ss.hasPermi('scp:notice:remove')")
    @Log(title = "系统通知", businessType = BusinessType.DELETE)
    @DeleteMapping("/gld/{noticeIds}")
    public AjaxResult removeGld(@PathVariable Long[] noticeIds)
    {
        return toAjax(csNoticeService.deleteCsNoticeByNoticeIds(noticeIds));
    }

    //根据用户id查询通知
//    @PreAuthorize("@ss.hasPermi('scp:notice:user:query')")
    @GetMapping("/user/gld/{userId}")
    public TableDataInfo getMoneyByUserId(@PathVariable Long userId)
    {
        startPage();
        List<CsNotice> list = csNoticeService.getNoticeByUserId(userId);
        return getDataTable(list);
    }

//    //根据通知id查询通知
//    @PreAuthorize("@ss.hasPermi('scp:notice:user:query')")
//    @GetMapping("/user/gld/{userId}")
//    public TableDataInfo getMoneyByUserId(@PathVariable Long userId)
//    {
//        startPage();
//        List<CsNotice> list = csNoticeService.getNoticeByUserId(userId);
//        return getDataTable(list);
//    }

    //轮播图
    @GetMapping("/index/lunbo")
    public AjaxResult selectAllCarImage()
    {
        List<CsNoticeVo> s = csNoticeService.selectAllNoticeImage();
        //从CsNoticeVo这个集合里面抽出Content这一个属性
        List<String> lunbos = s.stream().map(CsNoticeVo::getContent).collect(Collectors.toList());
        return AjaxResult.success(lunbos);
    }
    //新闻滚动条
    @GetMapping("/index/news")
    public AjaxResult selectNoticeNews()
    {
        List<String> s = csNoticeService.selectNoticeNews();
        //从CsNoticeVo这个集合里面抽出Content这一个属性
//        List<String> news = s.stream().map(CsNoticeVo::getContent).collect(Collectors.toList());
        return AjaxResult.success(s);
    }
//消息
    @GetMapping("/message")
    public TableDataInfo selectMessage() {
        System.out.println(666);
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<CsNoticeVo> csNoticeVos = csNoticeService.selectCsNotice(userId);
        System.out.println(csNoticeVos);
        return getDataTable(csNoticeVos);
    }
}
